﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using SlimDX;

using Vxl;
using Vxl.Drawables;
using SlimDX.Direct3D11;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using Vxl.Utils;

namespace VxlEditor
{
    public partial class VxlControl : UserControl
    {
        private bool isVxlInitialized = false;
        private Thread drawThread;

        public VxlControl()
        {
            InitializeComponent();            
        }

        public void CleanUp()
        {
            Stop();
        }

        public void Stop(){
            if(drawThread != null)
                drawThread.Abort();
        }

        public void Start(){
            if (drawThread == null || !drawThread.IsAlive)
            {
                drawThread = new Thread(new ThreadStart(DrawAndUpdate));
                drawThread.Start();
            }
        }

        public void InitializeVxlComponents(){
            InitializeVxlEngine();
            isVxlInitialized = true;

            VxlEngineSetupHelper.StartStopWatch();
            Start();
        }

        private void DrawAndUpdate(){
            while (drawThread.IsAlive)
            {
                try
                {
                    VxlEngineSetupHelper.RunOnce();
                }
                catch(SEHException e){
                    System.Console.Out.Write(e.StackTrace);
                }
                this.Invalidate();
            }
        }

        protected override void OnPaint(PaintEventArgs pea)
        {
            if (!isVxlInitialized || VxlEngineSetupHelper.dxDevice == null )
            {
                Graphics g = pea.Graphics;
                g.FillRectangle(Brushes.Black, new Rectangle(0, 0, Width, Height));
                return;
            }
        }

        protected override void OnPaintBackground(PaintEventArgs pea){
            // do nothing
        }

        private void InitializeVxlEngine(){
            VxlEngineSetupHelper.Setup(this);
        }

        private void VxlControl_SizeChanged(object sender, EventArgs e)
        {
            if (isVxlInitialized)
            {
                Stop();
                VxlEngineSetupHelper.Resize(this);
                //Globals.Device = VxlEngineSetupHelper.dxDevice;
                Globals.ActiveCamera.ResetProjection();
                Start();
            }
        }
    }
}
